<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Member_Model extends CI_Model {
	
	public function __construct() {
		$this->db->cache_delete_all();
		$this->load->helper("public");
		$this->load->helper("ip_helper");
	}
	/**
	 * [select_member_by_email 通过email]
	 * @param  [type] $email [description]
	 * @return [type]        [description]
	 */
	public function select_one_by_field($field, $value) {
		$this->db->select('*');
		$this->db->where($field, $value);
		$this->db->from('member');

		$query = $this->db->get();

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} else {
			return FALSE;
		}
	}

	public function isFailedTooMuch($passid) {
		$this->db->select('*');
		$this->db->where('passid', $passid);
		$this->db->from('member_failedlogin');

		$query = $this->db->get();

		if ($query->num_rows() > 0) {
			$result = $query->row_array();

			if ($result['lasttime'] < strtotime(date('Y-m-d')) ) {
				$data = array(
					'times' => 0,
					'lasttime' => strtotime(date('Y-m-d'))
					);
				$this->db->where('passid', $passid);
				$this->db->update('member_failedlogin', $data);
				return FALSE;
			}

			if ($result['times'] >= $this->config->item('maxFailedTimes')) {
				return TRUE;
			} else {
				return FALSE;
			}
		} else {
			return FALSE;
		}
	}

	public function add_failedlogin_times($passid) {
		//需要添加false，防止被转义
		$this->db->set('times', 'times + 1', FALSE);
		$this->db->where('passid', $passid);
		$this->db->update('member_failedlogin');
		$query = $this->db->get_where('member_failedlogin', array('passid' => $passid));
		$result = $query->row_array();
		return $this->config->item('maxFailedTimes') - intval($result['times']);
	}

	/**
	 * [update_member_status 更新用户的登陆次数登陆时间等]
	 * @param  [type] $passid [description]
	 * @return [type]         [description]
	 */
	public function update_member_status($passid) {
		$this->load->helper('ip');
		//需要添加false，防止被转义
		$this->db->set('logintimes', 'logintimes + 1', FALSE);
		$this->db->set('lastlogintime', time());
		$this->db->set('lastloginip', get_client_ip());
		$this->db->where('passid', $passid);
		$this->db->update('member_status');
	}

	public function get_default_role($passid, $first = 0) {
		$this->db->select('*');
		$this->db->where('pass_id', $passid);
		$this->db->where('isdefault', 1);

		$query = $this->db->get('member_role');

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} else {
			if ($first == 0) {
				return false;
			} else {
				$this->db->select('*');
				$this->db->where('pass_id', $passid);

				$query = $this->db->get('member_role');

				if ($query->num_rows() > 0) {
					return $query->row_array();
				} else {
					return false;
				}
			}
			
		}
	}
	
	public function get_roles_num($passid) {
		$this->db->select('*');
		$this->db->where('pass_id', $passid);
		$query = $this->db->get('member_role');
		
		return $query->num_rows();
	}

	public function get_profile($passid) {
		$this->db->select('*');
		$this->db->where('passid', $passid);
		//$this->db->where('realname', $realname);
		$this->db->from('member_profile');

		$query = $this->db->get();

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} else {
			return FALSE;
		}
	}

	public function insert_profile($result) {
		$data =array(
			'realname' => $result['user_name'],
			'idcard'   => $result['user_id'],
			'company'  => $result['user_depart'],
			'isused'   => 1
			);
		if (!empty($result['user_birth'])) {
			$timestamp = strtotime($result['user_birth']);
			$data['birthyear'] = date('Y', $timestamp);
			$data['birthmonth'] = date('m', $timestamp);
			$data['birthday'] = date('d', $timestamp);
		}

		$this->db->insert('member_profile', $data);
		return $this->db->insert_id();
	}

	public function clear_login_failed($passid) {
		$ths->db->set("times", "0");
		$this->db->where("passid", $passid);
		return $this->db->update("member_failedlogin");
	}

	// 往member表中插入一条记录
	public function insert_member($result) {
		$this->db->insert('member', $result);
		$passid = $this->db->insert_id();
		if (empty($passid)) {
			return FALSE;
		}

		return $passid;
	}

	public function get_autonym($idnumber) {
		$this->db->select("*");
		$this->db->where("idnumber", $idnumber);
		$this->db->from('member_autonym');

		$query = $this->db->get();

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} else {
			return FALSE;
		}
	}
	//创建一个论坛角色
	public function create_role($roledata) {
		$this->db->insert('member_role', $roledata);
		return $this->db->insert_id();
	}

	//根据passid 提取出对应的所有论坛账户
	public function get_roles($passid) {
		$this->db->select('*');
		$this->db->where('pass_id', $passid);
		$query = $this->db->get('member_role');

		if ($query->num_rows() > 0) {
			return $query->result_array();
		} else {
			return false;
		}
	}

	//绑定图书馆账号
	public function bind_lib_account($stuID, $password) {
		$this->db->select("*");
		$this->db->where("idnumber", $stuID);
		$query = $this->db->get("member_libaccount");

		if ($query->num_rows() > 0) {
			$this->db->set("password", $password);
			$this->db->where("idnumber", $stuID);
			return $this->db->update("member_libaccount");
		} else {
			$data = array(
				"idnumber" => $stuID,
				"password" => $password,
				"gmt_update" => time(),
				"logintimes" => 0
				);
			return $this->db->insert('member_libaccount', $data);
		}
	}

	//提取passid 对应的图书馆密码
	public function get_lib_password($idnumber) {
		$this->db->select("*");
		$this->db->where("idnumber", $idnumber);
		$query = $this->db->get("member_libaccount");

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} else {
			return FALSE;
		}
	}

	/*
	判断来源ip是否在被禁的表中
	 */
	public function check_ip_banned($passid, $ip) {
		$gmt_expired = time() - $this->config->item("ip_expired");
		$this->db->select("*");
		$this->db->where("ip", $ip);
		$this->db->where("pass_id", $passid);
		$this->db->where("gmt_banned >=", $gmt_expired);
		$query = $this->db->get("member_ipbanned");

		if ($query->num_rows() > 0) {
			return true;
		} else {
			return false;
		}
	}

	public function get_last_login_fails($passid, $ip) {
		$gmt_violence = time() - intval($this->config->item("gmt_violence"));

		$this->db->select("*");
		$this->db->where("pass_id", $passid);
		$this->db->where("ip", $ip);
		$this->db->where("gmt_login >=", $gmt_violence);
		$this->db->where("success", 1);
		$this->db->order_by("gmt_login", "desc");
		$query = $this->db->get("member_log");

		if ($query->num_rows() > 0) {
			$result = $query->row_array();
			$gmt_last_success = $result["gmt_login"];
		} else {
			$gmt_last_success = $gmt_violence;
		}


		$sql = "SELECT count(*) AS `failedTimes` FROM `pass_member_log` WHERE `pass_id` = ? AND `gmt_login` > ? AND `success` = '0'";
		$query = $this->db->query($sql, array($passid, $gmt_last_success));
		return $query->row_array();
	}

	/*
	登录日志插入，包括失败和成功，默认插入成功的
	 */
	public function insert_log($passid, $ip, $success = "1") {
		$data = array(
			"pass_id"   => $passid,
			"ip"        => $ip,
			"gmt_login" => time(),
			"success"   => $success
			);
		return $this->db->insert("member_log", $data);
	}

	public function insert_ipbanned($passid, $ip){
		$data = array(
			"pass_id"    => $passid,
			"ip"         => $ip,
			"gmt_banned" => time()
			);
		return $this->db->insert("member_ipbanned", $data);
	}

	public function set_default_role($passid, $roleID){
		$data = array(
			"isdefault" => "0"
			);
		$this->db->where("pass_id", $passid);
		$this->db->where("isdefault", "1");
		$this->db->update("member_role", $data);

		$data = array(
			"isdefault" => "1"
			);
		$this->db->where("pass_id", $passid);
		$this->db->where("id", $roleID);
		return $this->db->update("member_role", $data);
	}

	/*
		修改member表中的password
		如果密码一样，就不进行修改。
	 */
	public function update_password($passid, $password) {
		//这部分已经放在login中，可以避免多次重复查询
		/*$this->db->select("*");
		$this->db->where("id", $passid);
		$query = $this->db->get("member");

		if ($query->num_rows() < 0){
			return false;
		}
		$row = $query->row_array();
		//如果密码是一样的，则直接返回true，无需继续修改
		if (authcode($row["password"], "DECODE", $this->config->item("password_encode_key")) == $password) {
			return true;
		}*/

		$encodedPassword = authcode($password, "ENCODE", $this->config->item("password_encode_key"));

		$data = array(
			"password" => $encodedPassword
			);
		$this->db->where("id", $passid);
		return $this->db->update("member", $data);
	}

	public function send_mail($passid, $mail, $url = ""){
		$salt = getRandomString();
		$data = array(
			"passid"   => $passid,
			"mail"     => $mail,
			"salt"     => $salt,
			"gmt_post" => time(),
			"status"   => 0
			);
		if (!$this->db->insert("member_mailcheck", $data)) {
			return false;
		}
		$s = $passid."_".md5($salt.$passid.$salt);
		$token = authcode($s, "ENCODE", $this->config->item("password_encode_key"));
		$url = site_url("user/checkmail?token=".base64_encode($token)."&url=".urlencode($url));
		//$url = site_url("user/checkmail?token=".base64_encode($token)); 
		$this->email->from('aside99@sina.cn', 'zwb');
        $this->email->to($mail); 
        $this->email->subject("请激活您的账户");
        $this->email->message("<a href=\"".$url."\">请点击这里来激活你的邮箱</a>"); 

        if (!$this->email->send()) {
        	return false;
        } else {
        	return true;
        }
	}

	public function check_email($passid, $token){
		$this->db->select("*");
		$this->db->where("passid", $passid);
		$this->db->where("status", 0);
		$this->db->order_by("gmt_post", "DESC");
		$query = $this->db->get("member_mailcheck");

		if ($query->num_rows() > 0) {
			$row = $query->row_array();
		} else {
			log_message("error", "邮件激活：没有查找到邮件激活记录");
			return false;
		}

		if ((intval(time()) - intval($row["gmt_post"])) >= intval($this->config->item("mail_expire"))) {
			log_message("error", "邮件激活：链接过期");
			return false;
		}
		$s =  md5($row["salt"].$passid.$row["salt"]);
		if ($token != $s) {
			$row["status"] = 1;
			$this->db->where("passid", $passid);
			$this->db->update("member_mailcheck", $row);
			log_message("error", "邮件激活：token不正确");
			return false;
		} else {
			$data["status"] = 3;
			$this->db->where("id", $row["id"]);
			$this->db->update("member_mailcheck", $data);
			$data = array();
			$this->db->where("id", $passid);
			$data = array(
				"email" => $row["mail"],
				"emailstatus" => "1"
				);
			if (!$this->db->update("member", $data)) {
				log_message("error", "邮箱激活：修改member失败");
				return false;
			} else {
				return true;
			}
		}

	}

	public function check_old_passport($username, $password){
		$user = $this->select_user_from_old($username);

		if (empty($user)) {
			return false;
		} else {
			if ($password == $user["password"]) {
				return $user;
			} else {
				return false;
			}
		}
	}

	public function select_user_from_old($username) {
		$this->db->select("*");
		$this->db->where("user", $username);
		$query = $this->db->get("user");

		if ($query->num_rows() > 0) {
			return $query->row_array();
		} else {
			return false;
		}
	}

	public function translate($user, $stuID, $hdupassword) {
		if (!is_array($user)) {
			log_message("error", "member.translate()  user参数错误");
			show_error("参数错误");
		}
		$this->db->select("*");
		$this->db->where("username", $user["username"]);
		$query = $this->db->get("member");

		if ($query->num_rows() > 0) {
			$result = $query->row_array();
			if ($result["idnumber"] != "" || empty($result["idnumber"])) {
				log_message("error", "学号不为空".$result["idnumber"]);
				return false;
			}

			$r["idnumber"] = $stuID;
			$r["password"] = authcode($hdupassword, "ENCODE", $this->config->item("password_encode_key"));
			$this->db->where("id", $result["id"]);
			return $this->db->update("member", $r);
		} else {
			log_message("error", "转换：按用户名查找记录为空");
			return false;
		}
	}

	public function selectNotCheckMail($passid) {
		$this->db->select("*");
		$this->db->where("passid", $passid);
		$this->db->order_by("gmt_post", "DESC");
		$query = $this->db->get("member_mailcheck");
		
		if ($query->num_rows() > 0) {
			$result = $query->row_array();
			if ($result["status"] == 0) {
				return $result;
			} else {
				return FALSE;
			}
		} else {
			return FALSE;
		}
	}

	public function changeRolePassword($uc_id, $newPassword) {
		$uc_id = intval($uc_id);
		if (empty($uc_id)) {
			log_message("error", "changRolePassword，uc_id整化后为空");
			return false;
		}
		$this->db->where("uc_id", $uc_id);
		$r["uc_password"] = authcode($newPassword, "ENCODE", $this->config->itme("password_encode_key"));
		return $this->db->update("member_role", $r);
	}
}